import * as fs from "fs";
import argv from '../common/argv';

const appname = 'greendb'
const config = {
    appname,
    title: appname,
    apiDir: "api",
    mysql: {
        host: "127.0.0.1",
        port: 3306,
        user: "root",
        password: "123456",
        database: appname,
        connectionLimit: 50,
        supportBigNumbers: true,
        bigNumberStrings: false,
        charset: "utf8mb4"
    },
    email: {
        user: "admin@inu1255.cn",
        pass: ""
    },
    error: {
        "400": "非法的参数值、格式或类型",
        "401": "您尚未登录",
        "402": "功能尚未实现",
        "403": "没有权限",
        "404": "不存在"
    },
    upload: "public/tmp", // 文件上传目录
    secret: ('00000' + Math.floor(Math.random() * 1e9).toString(36)).slice(-6), // 加密字串
    code_expire: 600e3, // 验证码过期时间，10分钟
    port: 3000,
    dev: false, // 开发模式
    v: false, // 是否可见
    config_path: "config/.config.json",
    $save() {
        return new Promise((resolve, reject) => {
            console.log(`写入配置`);
            fs.writeFile(config.config_path, JSON.stringify(config, null, 2), err => (err ? reject(err) : resolve()));
        });
    },
    $load() {
        return new Promise((resolve, reject) => {
            fs.readFile(config.config_path, 'utf8', function(err, text) {
                load(text);
                resolve(!err)
            });
        });
    },
    $loadSync() {
        let text: string;
        try {
            text = fs.readFileSync(config.config_path, 'utf8')
        } catch (e) { }
        load(text)
    },
};

function load(text: string) {
    if (text) {
        try {
            let conf = JSON.parse(text)
            let write = false;
            for (let k in config) {
                if (k[0] != '$' && conf[k] === undefined) {
                    write = true;
                    break;
                }
            }
            Object.assign(config, conf);
            for (let k in argv) {
                if (config[k] != undefined && typeof config[k] != "object")
                    config[k] = argv[k];
            }
            if (write) config.$save();
        } catch (e) {
            console.error(`配置文件错误: `, e);
            process.exit(1)
        }
    } else {
        console.log("使用默认配置");
        config.$save();
    }
}

export default config;
